﻿namespace KinkumaFramework.FSharp.HelloWorld.ViewModel

open System
open System.Windows
open System.ComponentModel.DataAnnotations
open Microsoft.Practices.Prism.Interactivity.InteractionRequest
open Microsoft.Practices.Prism.Commands
open Okazuki.MVVM.PrismSupport.Interactivity
open Okazuki.MVVM.PrismSupport.FSharp
open KinkumaFramework.FSharp.HelloWorld.Model

/// MainWindow用のViewModel
type MainViewModel() as x =
    inherit FsValidatableViewModelBase()

    let mutable name = Unchecked.defaultof<string>

    let mutable selected = Unchecked.defaultof<string>

    let mutable alertCommand = Unchecked.defaultof<DelegateCommand>

    let alertRequest = InteractionRequest<ShowMessageBoxConfirmation>()

    do
        x.ValidateObject()

    /// 名前(必須入力項目)
    [<Required(ErrorMessage = "名前を入力してください")>]
    member x.Name
        with get() = name
        and set v = x.set(&name, v, <@ x.Name @>)

    /// 選択結果を表すメッセージ
    member x.Selected
        with get() = selected
        and set v = x.set(&selected, v, <@ x.Selected @>)

    /// Viewへ通知を行うためのInteractionRequest
    member x.AlertRequest = alertRequest

    /// ボタンが押された時のコマンド
    member x.AlertCommad = x.command(&alertCommand, x.AlertExecute, x.CanAlertExecute)

    /// コマンドの処理
    member private x.AlertExecute() =
        async {
            let message = greet x.Name
            let! result = x.AlertRequest.RaiseAsync(
                            ShowMessageBoxConfirmation(
                                Title = "確認", 
                                Content = greet x.Name, 
                                Button = Nullable<MessageBoxButton>(MessageBoxButton.OKCancel)))
            x.Selected <- match result.Confirmed with
                            | true -> "OKが押されました"
                            | false -> "Cancelが押されました"
        } |> Async.StartImmediate

    /// AlertCommandの実行可否判定
    member private x.CanAlertExecute() = not (x.HasErrors)